package com.fantastic.common.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * @author: rxx
 * @since: 2024/6/12 16:27
 * @description: 随机工具类
 */
public class RandomUtil {
    /**
     * 验证码键名
     */
    public static final String codeKey = "code";

    /**
     * 字母表
     */
    private final static String ALPHABET = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
    /**
     * 数字表
     */
    private final static String NUMBER = "1234567890";
    /**
     * 随机对象
     */
    private final static Random r = new Random();

    /**
     * 获取数字和字母混合字符串
     *
     * @param alphabetLength 字母长度
     * @param numberLength   数字长度
     * @return
     */
    public static String getCode(int alphabetLength, int numberLength) {
        String code = "";
        //获取字母
        code += getCodeAlphabet(alphabetLength);
        //获取数字
        code += getCodeNumber(numberLength);
        return getChaos(code).toString();
    }

    /**
     * 获取纯数字字符串
     *
     * @param length 字符串所需的长度
     * @return
     */
    public static String getCodeNumber(int length) {
        String code = "";
        for (int i = 0; i < length; i++) {
            code += NUMBER.charAt(r.nextInt(NUMBER.length()));
        }
        return code;
    }

    /**
     * 获取纯字母字符串
     *
     * @param length
     * @return
     */
    public static String getCodeAlphabet(int length) {
        String code = "";
        //获取字母
        for (int i = 0; i < length; i++) {
            code += ALPHABET.charAt(r.nextInt(ALPHABET.length()));
        }
        return code;
    }

    /**
     * 获取打乱的字符串
     *
     * @param chars 目标字符串
     * @return
     */
    public static StringBuilder getChaos(String chars) {
        // 将字符串转换为字符列表
        List<Character> charList = new ArrayList<>();
        for (char c : chars.toCharArray()) {
            charList.add(c);
        }
        // 打乱字符列表
        Collections.shuffle(charList);

        // 构建打乱后的字符串
        StringBuilder shuffledStr = new StringBuilder();
        for (char c : charList) {
            shuffledStr.append(c);
        }
        return shuffledStr;
    }

}
